from rest_framework import status, mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from .services_location import LocationService
from .serializers_location import (
    TechnicianLocationSerializer,
    ServiceAreaSerializer,
    LocationHistorySerializer,
    NearbyTechnicianSerializer
)
from .models import Technician


class LocationViewSet(GenericViewSet):
    """位置视图集"""
    permission_classes = [IsAuthenticated]

    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def update_location(self, request):
        """更新技师位置"""
        try:
            technician = request.user.technician_profile
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)

        serializer = TechnicianLocationSerializer(data=request.data)
        if serializer.is_valid():
            try:
                location = LocationService.update_technician_location(
                    technician=technician,
                    latitude=serializer.validated_data['latitude'],
                    longitude=serializer.validated_data['longitude'],
                    address=serializer.validated_data.get('address', '')
                )
                return Response(TechnicianLocationSerializer(location).data, status=status.HTTP_200_OK)
            except Exception as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def my_location(self, request):
        """获取技师当前位置"""
        try:
            technician = request.user.technician_profile
            location = LocationService.get_technician_location(technician)
            serializer = TechnicianLocationSerializer(location)
            return Response(serializer.data)
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)

    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def add_service_area(self, request):
        """添加服务区域"""
        try:
            technician = request.user.technician_profile
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)

        serializer = ServiceAreaSerializer(data=request.data)
        if serializer.is_valid():
            try:
                service_area = LocationService.add_service_area(technician, serializer.validated_data)
                return Response(ServiceAreaSerializer(service_area).data, status=status.HTTP_201_CREATED)
            except Exception as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def service_areas(self, request):
        """获取技师服务区域"""
        try:
            technician = request.user.technician_profile
            service_areas = LocationService.get_service_areas(technician)
            serializer = ServiceAreaSerializer(service_areas, many=True)
            return Response(serializer.data)
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)

    @action(detail=True, methods=['delete'], permission_classes=[IsAuthenticated])
    def delete_service_area(self, request, pk=None):
        """删除服务区域"""
        try:
            technician = request.user.technician_profile
            LocationService.delete_service_area(technician, pk)
            return Response({'message': '删除成功'}, status=status.HTTP_204_NO_CONTENT)
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def nearby(self, request):
        """获取附近技师"""
        # 获取用户位置参数
        try:
            latitude = float(request.GET.get('latitude'))
            longitude = float(request.GET.get('longitude'))
            max_distance = float(request.GET.get('max_distance', 10))  # 默认10公里
        except (TypeError, ValueError):
            return Response({'error': '请提供有效的经纬度参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))

        try:
            result = LocationService.get_nearby_technicians(
                latitude=latitude,
                longitude=longitude,
                max_distance=max_distance,
                page=page,
                page_size=page_size
            )
            return Response(result)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def location_history(self, request):
        """获取位置历史记录"""
        try:
            technician = request.user.technician_profile
            history = LocationService.get_location_history(technician)
            serializer = LocationHistorySerializer(history, many=True)
            return Response(serializer.data)
        except Technician.DoesNotExist:
            return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)
